package com.hainiu.cat.interview.juc;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * create by biji.zhao on 2021/7/11
 */
public class SemaphoreTest {

    public static void main(String[] args) {
        // 3个停车位
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 6; i++) {
           new Thread(() -> {
               String name = Thread.currentThread().getName();
               try {
                   semaphore.acquire();
                   System.out.println("线程" + name + "得到了停车位");
                   TimeUnit.SECONDS.sleep(2);
               } catch (Exception e) {
                   e.printStackTrace();
               }finally {
                   semaphore.release();
                   System.out.println("线程" + name + "离开了停车场");
               }
           }, "==="+ i + "============").start();
        }
    }
}
